package xyz.poke.business.tool.aspect;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import xyz.poke.business.tool.common.ErrorCode;
import xyz.poke.business.tool.common.Response;
import xyz.poke.business.tool.utils.ResponseUtils;

import java.util.stream.Collectors;

/**
 * 捕捉异常，给前端返回我们自定义的
 * @author 迫壳
 * @date 2024/3/3 21:00
 */
@RestControllerAdvice
@Log4j2
public class GlobalExceptionHandler {

    /**
     * 参数验证格式验证
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response<Boolean> handleIllegalArgumentException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        String result = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(";"));
        return ResponseUtils.fail(result,ErrorCode.PARAM_ERROR.getCode());
    }

}
